import socket
import time

HOST = ''
vPORT = 8080  # 访问端口
pPORT = 8001  # 监听接口

# 问题：没有处理各种突发情况，如客户端关闭连接。

print("""
       随感
今有通天柱，巍然入霄云。
引得东海水，复来华夏流。
于 宿舍
2022.5.9""")

vserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
vserver.bind((HOST, vPORT))
vserver.listen(1)
pserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
pserver.bind((HOST, pPORT))
pserver.listen(1)
print("waiting for connect")
pconn, paddr = pserver.accept()
pconn.settimeout(10)
print("pconnected by", paddr)


def getrequest(conn_):
    data_ = b""
    while True:
        try:
            s = conn_.recv(1024)
            data_ += s
        except socket.timeout:
            break
    print(data_)
    data_ = data_.split(b"\r\n")[0]
    return data_


def send(conn_, data_):
    conn_.sendall(data_)


while True:
    try:
        # print("waiting")
        conn, addr = vserver.accept()
        conn.settimeout(10)
    except socket.timeout:
        # print("continue1")
        continue
    # print("connected")
    data_ = b""
    while True:  # 这个接受放在函数里，超时在第三次请求中会失效。
        try:
            s = conn.recv(1024)
            # print(s)
            data_ += s
        except socket.timeout:
            # print("break")
            break
    data = data_.split(b"\r\n")[0].decode()
    try:
        method, filename, version = data.split(" ")
    except ValueError:
        continue
    print(addr[0], method, filename)

    text = "%s %s %s\n" % (method, filename, version)
    try:
        pconn.sendall(text.encode())
    except ConnectionResetError:
        send(conn, b'HTTP/1.1 200 OK\nContent-Type: text/html\n\nServer has been closed.\r\n')
        conn.close()
        print("waiting for connect")
        pconn, paddr = pserver.accept()
        pconn.settimeout(10)
        continue

    send(conn, b'HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
    while True:
        try:
            data = pconn.recv(1024)
        except socket.timeout:
            # send(conn, data)
            break
        send(conn, data)
    conn.close()
    # print("close")
